/**
 * @Description: 商品表SPU
 * @author ourslookAdmin
 * @date 2019-04-29 16:25:22
 */
import 'braft-editor/dist/index.css';
import 'braft-extensions/dist/table.css';
import React, { Fragment } from 'react';
import Modal from 'drag-modal';
import BraftEditor from 'braft-editor';
import Table1 from 'braft-extensions/dist/table';
import numeral from 'numeral';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Divider,
  Form,
  Icon,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Switch,
  Table,
  Tag,
  Tooltip,
  Transfer,
  TreeSelect,
  Upload,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import moment from 'moment';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import { handleEditorupload, editorPreview, editorProps } from '../../../utils/braft_editor_config';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const { MonthPicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const monthFormat = 'YYYY-MM';

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class Product extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '商品ID',
      width: 80,
      dataIndex: 'id',
      align: 'center',
      sorter: false,
      key: 'id',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      align: 'center',
      sorter: false,
      key: 'product_name',
    },
    {
      title: '商品图片',
      dataIndex: 'imageCover',
      align: 'center',
      width: 100,
      sorter: false,
      render: record => <DefaultImage src={record} />,
    },
    {
      title: '划线价格',
      dataIndex: 'originPriceMax',
      width: 120,
      align: 'right',
      sorter: true,
      key: 'origin_price_max',
      render: (value, record, index) => {
        if (value !== null && value !== undefined) {
          return `￥${numeral(value).format('0,0.00')}`;
        }
        return '-';
      },
    },
    {
      title: '微信二维码',
      dataIndex: 'wxQrCode',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === undefined ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            未生成
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            已生成
          </Tag>
        ),
    },
    { title: '创建时间', dataIndex: 'createTime', width: 200, align: 'center', key: 'createTime' },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'sort',
      fixed: 'right',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 180,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('mailproduct:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('mailproduct:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('mailproduct:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.copy();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />}>
              <Icon type="copy" />
            </Tooltip>
          </a>

          <Divider type="vertical" />

          <a
            hidden={!hasPermission('mailproduct:info')}
            onClick={() => {
              this.createWxImage(record, index);
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.createWxImage" defaultMessage="生成二维码" />
              }
            >
              <Icon type="file-image" />
            </Tooltip>
          </a>

          <Divider type="vertical" />

          <a
            hidden={!hasPermission('mailproduct:info')}
            onClick={() => {
              this.getSpec(record, index);
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.pushshopcar" defaultMessage="推送至购物车" />
              }
            >
              <Icon type="file-ppt" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Product.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      categoryList: [],
      contentHtml: BraftEditor.createEditorState(''),
      resKindIdList: [],
      productStatusVisible: false,
      productStatusModel: null,
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'productName',
      label: '商品名称',
      placeholder: '商品名称',
    },
    {
      type: 'SELECT',
      field: 'recommended',
      label: '是否首页推荐',
      placeholder: '是否首页推荐',
      list: [{ id: '', name: '请选择是否首页推荐' }],
    },
    {
      type: 'SELECT',
      field: 'status',
      label: '商品状态',
      placeholder: '商品状态',
      list: [{ id: '', name: '请选择商品状态' }],
    },
    {
      type: 'SELECT',
      field: 'asProduct',
      label: '是否正常商品',
      placeholder: '是否正常商品',
      list: [{ id: '', name: '请选择是否正常商品' }],
    },
    {
      type: 'SELECT',
      field: 'categoryId',
      label: '商品分类',
      placeholder: '商品分类',
      list: [{ id: '', name: '请选择商品分类' }],
    },
    {
      type: 'SELECT',
      field: 'resKindId',
      label: '在线资源',
      placeholder: '在线资源',
      list: [{ id: '', name: '请选择在线资源' }],
    },
  ];

  componentDidMount() {
    this.params.order = 'desc';
    this.params.sidx = 'sort';
    this.requestList();
    this.getCategoryTree();
    this.getResKindIdList();
    this.getRecommendedList();
    this.getStatusList();
    this.getAsProductList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params.order = 'desc';
    this.params.sidx = 'sort';
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        recommended: true,
        contentHtml: BraftEditor.createEditorState(''),
        deliveryType: 1,
        status: 2,
        asProduct: 1,
        asPostage: false,
        resKindId: '',
      },
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id, 'update');
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id, 'view');
  };

  copy = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }

    this.setState({
      editModalType: 'copy',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="复制" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id, 'copy');
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}mailproduct/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const mailProduct = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = mailProduct.id == null ? '/mailproduct/save' : '/mailproduct/update';
        mailProduct.resKindId = mailProduct.resKindId.join(',');

        if (mailProduct.description.isEmpty()) {
          uiUtils.showMessage(`商品详情不能为空！`, 'error');
          return;
        }

        const newCols = {};
        this.editForm.state.skuCols.forEach(item => {
          newCols[item.key] = item.title;
        });

        //实体中的attributeList（例如[{"价格":"1.00","原价":"1.00"}]），productSpecs（商品规格）字段赋值
        const attributeList = [];
        let inventorySum = 0;
        let displayPrice = 0;
        const flagTitle = [];
        for (let i = 0; i < this.editForm.state.skuRows.length; i += 1) {
          const productSpecs = [];
          const attribute = {};
          //库存综合
          inventorySum += Number(this.editForm.state.skuRows[i].inventory);
          //最低价格
          if (this.editForm.state.skuRows[i].price <= this.editForm.state.skuRows[0].price) {
            displayPrice = this.editForm.state.skuRows[i].price;
          }
          Object.keys(this.editForm.state.skuRows[i]).forEach(key => {
            if (
              (key === 'resEndDate' || key === 'resStartDate') &&
              mailProduct.resKindId !== '' &&
              mailProduct.resKindId !== undefined &&
              (this.editForm.state.skuRows[i][key] === '' ||
                this.editForm.state.skuRows[i][key] === undefined)
            ) {
              //当在线资源不为空的时候，开始日期和结束日期都不能为空
              flagTitle.push(false);
            }
            if (newCols[key] !== undefined) {
              attribute[newCols[key]] = this.editForm.state.skuRows[i][key];
            }
            if (key.indexOf('skuKey') !== -1 && newCols[key] !== undefined) {
              const obj = {};
              obj[newCols[key]] = this.editForm.state.skuRows[i][key];
              productSpecs.push(obj);
            }
          });
          if (productSpecs.length > 0) {
            this.editForm.state.skuRows[i].productSpecs = JSON.stringify(productSpecs);
          }
          attributeList.push(attribute);
        }
        if (flagTitle.length > 0) {
          uiUtils.showAlert('开始日期和结束日期不能为空！');
          return;
        }
        if (mailProduct.categorys !== undefined) {
          mailProduct.categorys = JSON.stringify(mailProduct.categorys);
        }
        if (attributeList.length > 0) {
          mailProduct.attributeList = JSON.stringify(attributeList);
        }
        if (mailProduct.shelvesTime !== undefined && mailProduct.status === 0) {
          mailProduct.shelvesTime = `${mailProduct.shelvesTime.format('YYYY-MM-DD HH:mm:ss')}`;
        }

        let images = '';
        for (let i = 0; i < this.editForm.state.iconList.length; i += 1) {
          if (this.editForm.state.imgList.length <= 0) {
            //如果不上传封面图片，默认相册图片的第一张
            mailProduct.imageCover = this.editForm.state.iconList[0].response.object;
          }
          let item = '';
          if (i === this.editForm.state.iconList.length - 1) {
            item = this.editForm.state.iconList[i].response.object;
          } else {
            item = `${this.editForm.state.iconList[i].response.object},`;
          }
          images += item;
        }
        mailProduct.images = images;

        //将删除的规格数据添加到skuRows，后台通过status字段判断，进行删除
        const { skuRows: newSkuRows } = this.editForm.state;
        if (this.editForm.state.delSpecIds > 0) {
          for (let i = 0; i < this.editForm.state.delSpecIds.length; i += 1) {
            newSkuRows.push({ id: this.editForm.state.delSpecIds[i], status: '3' });
          }
        }
        //组合规格key与规格value
        if (this.editForm.state.skuKeys.length > 0) {
          for (let i = 0; i < this.editForm.state.skuKeys.length; i += 1) {
            const value = [];
            if (this.editForm.state.skuKeys[i].specValue !== undefined) {
              for (let j = 0; j < this.editForm.state.skuKeys[i].specValue.length; j += 1) {
                value.push(this.editForm.state.skuKeys[i].specValue[j].value);
              }
              if (value.length > 0) {
                this.editForm.state.skuKeys[i].value = JSON.stringify(value);
              }
            }
          }
        }

        mailProduct.productSpecs = newSkuRows;
        mailProduct.specKeys = this.editForm.state.skuKeys.filter(
          (en, index) => !(en.id === undefined && en.status === 3)
        );
        mailProduct.description = mailProduct.description.toHTML();
        mailProduct.inventorySum = inventorySum;
        mailProduct.displayPrice = displayPrice;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: mailProduct,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!mailProduct.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  reback = () => {
    this.editForm.props.form.resetFields();
    this.setState({ showList: 1 });
    this.editForm.setState({
      skuCols: this.editForm.getDefalutCols(),
      skuRows: [],
      skuKeys: [],
    });
    this.setState({
      contentHtml: BraftEditor.createEditorState(''),
    });
  };

  getInfo = (id, type) => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(`${getWebPath(`/mailproduct/infoVo/${id}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });

      if (res && res.code === 0) {
        const mailProduct = res.mailProduct;
        mailProduct.sort = `${mailProduct.sort}`;
        if (type !== 'view') {
          if (mailProduct.categorys !== undefined && this.props.type !== 'add') {
            mailProduct.categorys = JSON.parse(mailProduct.categorys);
          }
        }

        if (type === 'copy') {
          mailProduct.id = null;
          mailProduct.productName = `${mailProduct.productName}__1`;
        }
        if (mailProduct.resKindId) {
          mailProduct.resKindId = mailProduct.resKindId.split(',');
        }
        this.setState({
          editModel: mailProduct,
          contentHtml: BraftEditor.createEditorState(mailProduct.description),
        });

        for (let i = 0; i < mailProduct.specKeys.length; i += 1) {
          const specKey = mailProduct.specKeys[i];
          const key1 = `skuKey${i}`;
          if (type === 'copy') {
            mailProduct.specKeys[i].id = null;
          }
          if (specKey.value !== undefined && specKey.value !== '') {
            specKey.specValue = [];
            const specValues = JSON.parse(specKey.value);
            for (let j = 0; j < specValues.length; j += 1) {
              specKey.specValue.push({ code: j, value: specValues[j] });
            }
          }
          for (let j = 0; j < this.editForm.state.skuCols.length; j += 1) {
            if (this.editForm.state.skuCols[j].key === key1) {
              this.editForm.state.skuCols[j].title = specKey.name;
            }
          }

          this.editForm.state.skuCols.unshift({
            title: specKey.name,
            key: key1,
            dataIndex: key1,
            render: (text, recode, newindex) => {
              let specVal = '';
              if (recode.productSpecs !== undefined) {
                const productSpecs = JSON.parse(recode.productSpecs);
                for (let k = 0; k < productSpecs.length; k += 1) {
                  const name = specKey.name;
                  const productSpecKeys = Object.keys(productSpecs[k]);
                  for (let z = 0; z < productSpecKeys.length; z += 1) {
                    if (productSpecKeys[z] === name) {
                      specVal = productSpecs[k][name];
                      break;
                    }
                  }
                }
              }
              if (type === 'copy') {
                recode.id = null;
              }
              if (text == null) {
                recode[key1] = specVal;
              }
              return (
                <FormItem style={{ margin: 0 }}>
                  {this.editForm.props.form.getFieldDecorator(`${key1}-${newindex}`, {
                    rules: [
                      {
                        required: true,
                        message: '请输入规格值',
                      },
                    ],
                    initialValue: text === null || text === undefined ? specVal : text,
                  })(
                    <Input
                      disabled={type === 'view'}
                      onChange={event => {
                        recode[key1] = event.currentTarget.value;
                        if (specKey.specValue !== undefined && specKey.specValue.length > 0) {
                          for (let k = 0; k < specKey.specValue.length; k += 1) {
                            if (specKey.specValue[k].code === newindex) {
                              specKey.specValue[k].value = event.currentTarget.value;
                              return;
                            }
                          }
                          specKey.specValue.push({
                            code: newindex,
                            value: event.currentTarget.value,
                          });
                        }
                      }}
                    />
                  )}
                </FormItem>
              );
            },
          });
        }

        const { skuCols: newSkuCols } = this.editForm.state;

        for (let i = 0; i < mailProduct.productSpecs.length; i += 1) {
          if (mailProduct.productSpecs[i].resStartDate === undefined) {
            mailProduct.productSpecs[i].resStartDate = '';
          }
          if (mailProduct.productSpecs[i].resEndDate === undefined) {
            mailProduct.productSpecs[i].resEndDate = '';
          }
        }

        this.editForm.setState({
          skuCols: newSkuCols,
          skuRows: mailProduct.productSpecs,
          skuKeys: mailProduct.specKeys,
        });
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  createWxImage = (record, index) => {
    //此处如果它的类型值为空， 为了不让下面的接口出现异常，这里传入-1， -1 在接口中也代表该值不存在
    if (!record.promotionType) {
      record.promotionType = -1;
    }
    if (record.wxQrCode) {
      uiUtils.showConfirm(formatMessage({ id: '已经存在二维码，是否再次生成？' }), () => {
        requestPromise(
          `${getWebPath(
            `/mailproduct/createWxImage?id=${record.id}&promotionType=${record.promotionType}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    } else {
      uiUtils.showConfirm(formatMessage({ id: '是否生成二维码？' }), () => {
        requestPromise(
          `${getWebPath(
            `/mailproduct/createWxImage?id=${record.id}&promotionType=${record.promotionType}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    }
  };

  pushShopCar = () => {
    if (this.state.specIds === undefined) {
      uiUtils.showAlert('请先选择规格');
      return;
    }
    this.getUserList();
    this.setState({
      visible: true,
    });
  };

  getSpec = (record, index) => {
    /*const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }*/
    this.requestSpecList(record.id);
    this.setState({
      galleryModelVisible: true,
      specDatas: [],
    });
  };

  requestSpecList = productId => {
    const columns = [
      {
        title: '规格',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
      },
    ];
    this.setState({
      specColumns: columns,
    });
    requestPromise(
      `${getWebPath(
        `/mailproductspec/list?productId=${productId === undefined ? '' : productId}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const results = res.page.list;
        const datas = [];
        results.forEach(r => {
          if (r.productSpecs !== undefined) {
            const productSpecs = JSON.parse(r.productSpecs);
            let productss = '';
            productSpecs.forEach(s => {
              // eslint-disable-next-line guard-for-in,no-restricted-syntax
              for (const key in s) {
                productss = productss === '' ? s[key] : `${productss},${s[key]}`;
              }
            });
            r.productSpecs = productss;
          } else {
            r.productSpecs = '默认规格';
          }
          const data = {
            key: r.id,
            name: r.productSpecs,
            value: r.productSpecs,
            price: r.price,
          };
          datas.push(data);
        });
        this.setState({
          specDatas: datas,
        });
      }
    });
  };

  handleChange = targetKeys => {
    this.setState({ targetKeys });
  };

  //获取用户list
  getUserList = (dir, key) => {
    requestPromise(`${getWebPath(`/user/listVo`)}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const userList = res.users;
        const userDatas = [];
        userList.forEach(r => {
          const data = {
            key: r.userId,
            title: `${r.username} - ${r.mobile}`,
            description: `${r.username} - ${r.mobile}`,
            chosen: Math.random() * 2 > 1,
          };
          // if (data.chosen) {
          //   targetKeys.push(data.key);
          // }
          userDatas.push(data);
        });
        this.setState({
          userDatas,
        });
      }
    });
  };

  filterOption = (inputValue, option) =>
    option.description.indexOf(inputValue) > -1 ||
    option.description.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;

  handleOk = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }
    const userIdss = this.state.targetKeys;
    this.setState({
      confirmLoading: true,
    });
    const datas = {
      productIds: ids,
      specIds: this.state.specIds,
      userIds: userIdss,
    };
    requestPromise(`${getWebPath('/mailproduct/sendProductToShopCar')}`, {
      method: 'POST',
      body: datas,
    }).then(res => {
      this.setState({
        confirmLoading: false,
        visible: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.setState({
          showList: 1,
          galleryModelVisible: false,
        });

        //新增重新置为第一页
        // this.requestList();
      }
    });
  };

  getProductSatus = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    this.setState({
      productStatusVisible: true,
      productStatusModel: {
        status: 2,
      },
    });
  };

  updateProductSatus = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    let flag = true;
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
      if (selectedRows[i].status === this.state.productStatusModel.status) {
        flag = false;
        uiUtils.showMessage(
          `批量操作的商品，商品状态已经和要更改的商品状态一致，不能继续操作！`,
          'error'
        );
        break;
      }
    }

    if (flag) {
      const data = {
        modelIds: ids.join(','),
        status: this.state.productStatusModel.status,
      };

      this.updateProductSatusForm.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({
            productStatusLoading: true,
          });
          requestPromise(`${getWebPath()}/mailproduct/operateMailProductByIds`, {
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            body: data,
          }).then(res => {
            if (res && res.code === 0) {
              this.setState({
                productStatusVisible: false,
                productStatusLoading: false,
              });
              uiUtils.showMessage(
                formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
                'success'
              );
              this.setState({
                showList: 1,
              });
              this.requestList();
            }
          });
        }
      });
    }
  };
  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    this.setState({ list: null });
    requestLists(this, `${getWebPath()}mailproduct/list`, this.params);
  };

  getCategoryTree = () => {
    requestPromise(`${getWebPath('/mailcategory/list')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const categoryIds = res.page.list || [];
        const newCategoryIds = [
          { id: '', name: '请选择商品分类' },
          ...categoryIds.map(e => ({ id: e.id, name: e.name })),
        ];
        const formItem = this.findFormListItemByField('categoryId');
        formItem.list = newCategoryIds;
        this.setState({
          categoryList: res.page.list,
        });
      }
    });
  };

  getResKindIdList = () => {
    requestPromise(`${getWebPath('/busonlinereskinds/list')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const resKindIds = res.page.list || [];
        const newResKindIds = [...resKindIds.map(e => ({ id: e.id, name: e.name }))];
        const formItem = this.findFormListItemByField('resKindId');
        formItem.list = newResKindIds;
        this.setState({
          resKindIdList: newResKindIds,
        });
      }
    });
  };

  getRecommendedList = () => {
    const newRecommended = [
      { id: '', name: '请选择是否首页推荐' },
      { id: '1', name: '是' },
      { id: '0', name: '否' },
    ];
    const formItem = this.findFormListItemByField('recommended');
    formItem.list = newRecommended;
  };

  getStatusList = () => {
    const newStatus = [
      { id: '', name: '请选择商品状态' },
      { id: '2', name: '上架' },
      { id: '0', name: '自定义上架时间' },
      { id: '1', name: '暂不售卖，放入仓库' },
    ];
    const formItem = this.findFormListItemByField('status');
    formItem.list = newStatus;
  };

  getAsProductList = () => {
    const newStatus = [
      { id: '', name: '请选择是否正常商品' },
      { id: 'true', name: '正常商品' },
      { id: 'false', name: '配件或赠品销售' },
    ];
    const formItem = this.findFormListItemByField('asProduct');
    formItem.list = newStatus;
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        const ids = [];
        for (let i = 0; i < selectedRows.length; i += 1) {
          ids.push(selectedRows[i].key);
        }
        this.setState({
          specIds: ids,
        });
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('mailproduct:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('mailproduct:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
            <Button type="default" icon="info-circle" {...style} onClick={this.getProductSatus}>
              <FormattedMessage
                id="ours.curd.list.updateproductstatus"
                defaultMessage="批量上下架"
              />
            </Button>
            {/*<Button type="default" icon="info-circle" {...style} onClick={this.getSpec}>
              <FormattedMessage id="ours.curd.list.pushshopcar" defaultMessage="推送至购物车" />
            </Button>*/}
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1200 }}
            />
          </div>
        </Card>

        <BackTop />

        <Modal
          width={700}
          height={500}
          visible={this.state.galleryModelVisible}
          title="选择规格"
          onCancel={() => {
            this.setState({
              galleryModelVisible: false,
            });
          }}
          onOk={this.pushShopCar}
          confirmLoading={this.state.confirmLoading}
          saveDistance={0}
          destroyOnClose
        >
          <Table
            rowSelection={rowSelection}
            columns={this.state.specColumns}
            dataSource={this.state.specDatas}
          />
        </Modal>

        {/*选择推送用户对话框*/}
        <Modal
          width={700}
          height={500}
          visible={this.state.visible}
          title="选择用户"
          onCancel={() => {
            this.setState({
              visible: false,
            });
          }}
          onOk={this.handleOk}
          confirmLoading={this.state.confirmLoading}
          saveDistance={0}
          destroyOnClose
        >
          <Transfer
            dataSource={this.state.userDatas}
            showSearch
            listStyle={{
              width: 250,
              height: 300,
            }}
            filterOption={this.filterOption}
            operations={['>>', '<<']}
            targetKeys={this.state.targetKeys}
            onChange={this.handleChange}
            //onSearch={this.getUserList}
            render={item => `${item.title}`}
            footer={this.renderFooter}
          />
        </Modal>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button style={{ marginRight: '18px' }} onClick={this.reback}>
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                categoryList={this.state.categoryList}
                contentHtml={this.state.contentHtml}
                resKindIdList={this.state.resKindIdList}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
        <UpdateProductSatusForm
          onOk={() => {
            this.updateProductSatus();
          }}
          onCancel={() => {
            this.setState({ productStatusVisible: false });
          }}
          productStatusModel={this.state.productStatusModel}
          visible={this.state.productStatusVisible}
          productStatusLoading={this.state.productStatusLoading}
          wrappedComponentRef={inst => {
            this.updateProductSatusForm = inst;
          }}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Product;

class UpdateProductSatusForm extends React.Component {
  static propTypes = {
    productStatusModel: PropTypes.object,
    visible: PropTypes.bool,
    productStatusLoading: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func,
  };

  static defaultProps = {
    productStatusModel: null,
    visible: false,
    productStatusLoading: false,
    onCancel: () => {},
    onOk: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const productStatusLoading = this.props.productStatusLoading;
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onOk = this.props.onOk;
    const productStatusModel = this.props.productStatusModel || {};

    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少壹個柵格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每壹col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之間的間隔?px
    //校驗文檔：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Modal
        title="批量上下架"
        visible={visible}
        onCancel={onCancel}
        onOk={onOk}
        destroyOnClose
        closable
        width={600}
        saveDistance={0}
        confirmLoading={productStatusLoading}
      >
        <Form layout="horizontal">
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="商品状态" {...formItemLayout}>
                {getFieldDecorator('status', {
                  initialValue: productStatusModel.status,
                  rules: [
                    {
                      required: true,
                      message: '商品状态必選',
                    },
                  ],
                })(
                  <Select
                    placeholder="请选择"
                    style={{ width: 250 }}
                    onChange={value => {
                      productStatusModel.status = value;
                    }}
                  >
                    <option value={2}>上架</option>
                    <option value={1}>暂不售卖，放入仓库</option>
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }
}

/* eslint-disable no-class-assign */
//無更多的綁定， 請用 @Form.create() 註解替換
UpdateProductSatusForm = Form.create({})(UpdateProductSatusForm);

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    categoryList: PropTypes.object,
    contentHtml: PropTypes.object,
    resKindIdList: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    categoryList: [],
    contentHtml: BraftEditor.createEditorState(''),
    resKindIdList: [],
  };

  constructor(props) {
    super(props);
    const defaultIconList = this.getDefalutIcons();
    const defaultImgList = this.props.model.imageCover
      ? [
          {
            uid: '1',
            name: '',
            status: 'done',
            type: 'image/',
            url: this.props.model.imageCover,
            response: {
              object: this.props.model.imageCover,
            },
          },
        ]
      : null; //defaultFileList
    this.state = {
      previewIconVisible: false, //上传文件预览
      previewIcon: '', //上传文件预览
      defaultIconList, //上传文件列表
      iconList: defaultIconList && defaultIconList.length > 0 ? defaultIconList : [],
      previewImgVisible: false, //上传文件预览
      previewImg: '', //上传文件预览
      defaultImgList, //上传文件列表
      imgList: defaultImgList && defaultImgList.length > 0 ? [defaultImgList[0]] : [],
      skuCols: this.getDefalutCols(),
      skuRows: this.getDefualtRows(),
      skuKeys: [],
      delSpecIds: [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getDefalutIcons = () => {
    let defalutIcons = null;
    if (this.props.model.images) {
      defalutIcons = [];
      for (let i = 0; i < this.props.model.images.split(',').length; i += 1) {
        defalutIcons.push({
          uid: i + 1,
          name: '',
          status: 'done',
          type: 'image/',
          url: this.props.model.images.split(',')[i],
          response: {
            object: this.props.model.images.split(',')[i],
          },
        });
      }
    }
    return defalutIcons;
  };

  getDefualtRows = () => {
    const defualtRows = [];
    if (this.props.type === 'add') {
      defualtRows.push({
        price: '',
        inventory: '',
        coding: '',
        barcode: '',
        originalPrice: '',
        grouponPrice: '',
        resStartDate: '',
        resEndDate: '',
      });
    }
    return defualtRows;
  };

  getDefalutCols = () => {
    const cols = [
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`price-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入价格',
                },
                rulesReg('money_0_999999'),
              ],
              initialValue: text,
            })(
              <Input
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].price = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '库存',
        dataIndex: 'inventory',
        key: 'inventory',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`inventory-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入库存',
                },
                {
                  max: 11,
                  message: '最长11个字符',
                },
              ],
              initialValue: text,
            })(
              <Input
                defaultValue={text}
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].inventory = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '原价',
        dataIndex: 'originalPrice',
        key: 'originalPrice',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`originalPrice-${index}`, {
              rules: [
                {
                  required: true,
                  message: '请输入原价',
                },
                rulesReg('money_0_999999'),
              ],
              initialValue: text,
            })(
              <Input
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].originalPrice = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '编码',
        dataIndex: 'coding',
        key: 'coding',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`coding-${index}`, {
              rules: [
                {
                  max: 32,
                  message: '最长32个字符',
                },
              ],
              initialValue: text,
            })(
              <Input
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].coding = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '条形码',
        dataIndex: 'barcode',
        key: 'barcode',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`barcode-${index}`, {
              rules: [
                {
                  max: 32,
                  message: '最长32个字符',
                },
              ],
              initialValue: text,
            })(
              <Input
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].barcode = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '拼团价',
        dataIndex: 'grouponPrice',
        key: 'grouponPrice',
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            {this.props.form.getFieldDecorator(`grouponPrice-${index}`, {
              rules: [rulesReg('money_0_999999')],
              initialValue: text,
            })(
              <Input
                disabled={this.props.type === 'view'}
                onChange={e => {
                  this.state.skuRows[index].grouponPrice = e.target.value;
                }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '开始日期',
        dataIndex: 'resStartDate',
        key: 'resStartDate',
        width: 130,
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            <MonthPicker
              format={monthFormat}
              placeholder="请选择"
              defaultValue={
                recode.resStartDate === undefined || recode.resStartDate === ''
                  ? ''
                  : moment(recode.resStartDate, 'YYYY-MM')
              }
              onChange={e => {
                if (e === null) {
                  this.state.skuRows[index].resStartDate = '';
                } else {
                  this.state.skuRows[index].resStartDate = `${e.format('YYYY-MM')}-01`;
                }
              }}
            />
          </FormItem>
        ),
      },
      {
        title: '结束日期',
        dataIndex: 'resEndDate',
        key: 'resEndDate',
        width: 130,
        render: (text, recode, index) => (
          <FormItem style={{ margin: 0 }}>
            <MonthPicker
              format={monthFormat}
              placeholder="请选择"
              defaultValue={
                recode.resEndDate === undefined || recode.resEndDate === ''
                  ? ''
                  : moment(recode.resEndDate, 'YYYY-MM')
              }
              onChange={e => {
                if (e === null) {
                  this.state.skuRows[index].resEndDate = '';
                } else {
                  this.state.skuRows[index].resEndDate = `${e.format('YYYY-MM')}-31`;
                }
              }}
            />
          </FormItem>
        ),
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 160,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={index === 0 || this.props.type === 'view'}
              onClick={() => {
                this.specCopy(record);
              }}
            >
              <Tooltip title={<FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />}>
                <Icon type="copy" />
              </Tooltip>
            </a>
            <Divider type="vertical" />
            <a
              hidden={index === 0 || this.props.type === 'view'}
              onClick={() => {
                this.specDel(record, index);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
              >
                <Icon type="delete" />
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];
    return cols;
  };

  specCopy = record => {
    const { skuRows: newSkuRows } = this.state;
    record.id = null;
    newSkuRows.push(record);
    this.setState({
      skuRows: newSkuRows,
    });
  };

  specDel = (record, index) => {
    const { skuRows: newSkuRows, delSpecIds: newDelSpecIds } = this.state;
    if (record.id !== null && record.id !== undefined) {
      newDelSpecIds.push(record.id);
    }
    //需要删除specKeys中对应的规格值
    if (this.state.skuKeys.length > 0) {
      for (let i = 0; i < this.state.skuKeys.length; i += 1) {
        if (
          this.state.skuKeys[i].specValue !== undefined &&
          this.state.skuKeys[i].specValue.length > 0
        ) {
          this.state.skuKeys[i].specValue.splice(index, 1);
        }
      }
    }
    newSkuRows.splice(index, 1);
    this.setState({
      skuRows: newSkuRows,
      delSpecIds: newDelSpecIds,
    });
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  getCategoryName = categorys => {
    const categoryName = [];
    if (categorys !== undefined && this.props.type !== 'add') {
      const categoryIds = JSON.parse(categorys);
      for (let i = 0; i < categoryIds.length; i += 1) {
        for (let j = 0; j < this.props.categoryList.length; j += 1) {
          if (this.props.categoryList[j].id === categoryIds[i]) {
            const item = this.props.categoryList[j].name;
            categoryName.push(item);
          }
        }
      }
    }
    return categoryName;
  };

  categoryFindByParent = id => {
    const rootCategorys = this.props.categoryList
      .filter((en, index) => en.pid === id)
      .map(en => ({
        title: en.name,
        key: en.id,
        value: en.id,
      }));
    return rootCategorys || [];
  };

  categoryConversionList = () => {
    const rootCategorys = this.categoryFindByParent(0);
    //递归获取子菜单
    this.categoryFindTreeList(rootCategorys);
    //外层包裹一下
    return rootCategorys;
  };

  categoryFindTreeList = categorys => {
    const subCategoryList = [];
    for (let i = 0; i < categorys.length; i += 1) {
      const category = categorys[i];
      category.children = this.categoryFindTreeList(this.categoryFindByParent(category.key));
      subCategoryList.push(category);
    }
    return subCategoryList;
  };

  handleUploadIconPreview = file => {
    const previewIcon = file.url || file.thumbUrl;
    const previewIconVisible = file.type.startsWith('image/');
    this.setState({
      previewIcon,
      previewIconVisible,
    });
  };

  handleUploadIconOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      iconList: [],
      defaultIconList: null,
    });
  };

  handleUploadIconOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        iconList: info.fileList,
      });
      if (response) {
        uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
        setTimeout(() => {
          this.props.form.setFieldsValue({
            images: response.object,
          });
          if (loadingCallback) {
            loadingCallback(false);
          }
        }, 500);
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  handleUploadImgOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      imgList: [],
      defaultImgList: null,
    });
  };

  handleUploadImgOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        imgList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              imageCover: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  handleUploadImgPreview = file => {
    const previewImg = file.url || file.thumbUrl;
    const previewImgVisible = true;
    this.setState({
      previewImg,
      previewImgVisible,
    });
  };

  addSkuKey = () => {
    if (this.state.skuKeys.filter(en => en.status !== 3).length >= 3) {
      uiUtils.showMessage(`最多添加3列规格`, 'error');
    } else {
      const item = { name: '', specValue: [] };
      const { skuKeys: newSkukeys } = this.state;
      newSkukeys.push(item);
      this.setState({
        skuKeys: newSkukeys,
      });
    }
  };

  delSkuKey = (item, index) => {
    const { skuKeys: newSkukeys, skuCols: newSkuCols, skuRows: newSkuRows } = this.state;
    //newSkukeys.splice(index,1);
    newSkukeys[index].status = 3;

    if (newSkuCols.length > 0) {
      for (let i = 0; i < newSkuCols.length; i += 1) {
        if (newSkuCols[i].key === `skuKey${index}`) {
          newSkuCols.splice(i, 1);
          break;
        }
      }
    }

    for (let i = 0; i < newSkuRows.length; i += 1) {
      if (newSkuRows[i].productSpecs !== undefined) {
        const productSpecs = JSON.parse(newSkuRows[i].productSpecs);
        for (let j = 0; j < productSpecs.length; j += 1) {
          // eslint-disable-next-line no-prototype-builtins
          if (productSpecs[j].hasOwnProperty(newSkukeys[index].name)) {
            productSpecs.splice(j, 1);
            break;
          }
        }
        if (productSpecs.length === 0) {
          newSkuRows[i].productSpecs = '';
        } else {
          newSkuRows[i].productSpecs = JSON.stringify(productSpecs);
        }
      }
      delete newSkuRows[i][`skuKey${index}`];
    }

    this.setState({
      skuKeys: newSkukeys,
      skuCols: newSkuCols,
      skuRows: newSkuRows,
    });
  };

  addRow = () => {
    if (this.state.skuKeys.length === 0) {
      uiUtils.showMessage(`没有添加规格的时候，只能有一条默认规格明细！`, 'error');
    } else {
      const { skuRows: newSkuRows } = this.state;
      newSkuRows.push({
        price: '',
        inventory: '',
        coding: '',
        barcode: '',
        originalPrice: '',
      });
      this.setState({
        skuRows: newSkuRows,
      });
    }
  };

  getDeliveryTypeName = deliveryType => {
    let deliveryTypeName = '';
    if (deliveryType === 1) {
      deliveryTypeName = '统一运费';
    } else if (deliveryType === 2) {
      deliveryTypeName = '满x包邮，否则y元';
    } else if (deliveryType === 3) {
      deliveryTypeName = '满xx件包邮，否则yy元';
    } else if (deliveryType === 4) {
      deliveryTypeName = '运费模板';
    }
    return deliveryTypeName;
  };

  getStatusName = status => {
    let statusName = '';
    if (status === 0) {
      statusName = '自定义上架时间';
    } else if (status === 1) {
      statusName = '暂不售卖，放入仓库';
    } else if (status === 2) {
      statusName = '上架';
    }
    return statusName;
  };

  preview = () => {
    editorPreview(this.state.editorState.toHTML());
  };

  splitStr = str => {
    const idList = [];
    // eslint-disable-next-line no-restricted-syntax
    for (const string of str.toString().split(',')) {
      idList.push(Number(string));
    }
    return idList;
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const braftEditorFormItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 18 },
    };
    const braftEditorLayout = { sm: 40 };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const imageCoverProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'product', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadImgOnChange,
      onRemove: this.handleUploadImgOnRemove,
      defaultFileList: this.state.defaultImgList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };
    const iconProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'product', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadIconOnChange,
      onRemove: this.handleUploadIconOnRemove,
      defaultFileList: this.state.defaultIconList,
      multiple: true,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const divStyle = {
      border: '1px solid #d1d1d1',
      borderRadius: '5px',
    };

    const { Column } = Table;

    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };

    const options = {
      defaultColumns: 3, // 默认列数
      defaultRows: 3, // 默认行数
      withDropdown: false, // 插入表格前是否弹出下拉菜单
      exportAttrString: '', // 指定输出HTML时附加到table标签上的属性字符串
      // includeEditors: ['editor-id-1'], // 指定该模块对哪些BraftEditor生效，不传此属性则对所有BraftEditor有效
      excludeEditors: ['editor-id-2'], // 指定该模块对哪些BraftEditor无效
    };

    BraftEditor.use(Table1(options));

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <div className="demo-container">
        <Form layout="horizontal">
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="商品名称" {...formItemLayout}>
                {type === 'view'
                  ? model.productName
                  : getFieldDecorator('productName', {
                      initialValue: model.productName,
                      rules: [
                        {
                          required: true,
                          message: '商品名称必填',
                        },
                        {
                          max: 128,
                          message: '最长128个字符',
                        },
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="商品名称" />)}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="商品分类" {...formItemLayout}>
                {type === 'view'
                  ? this.getCategoryName(model.categorys)
                  : getFieldDecorator('categorys', {
                      initialValue: model.categorys,
                      rules: [
                        {
                          required: true,
                          message: '商品分类必选',
                        },
                      ],
                    })(
                      <TreeSelect
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        treeData={this.categoryConversionList()}
                        placeholder="可选择"
                        treeDefaultExpandAll={false}
                        showSearch
                        multiple
                        treeNodeLabelProp="title"
                        treeNodeFilterProp="title"
                      />
                    )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="划线价格" {...formItemLayout}>
                {type === 'view'
                  ? `￥${numeral(model.originPriceMax).format('0,0.00')}`
                  : getFieldDecorator('originPriceMax', {
                      initialValue: model.originPriceMax,
                      rules: [rulesReg('money_0_999999')],
                    })(
                      <Input
                        addonBefore="￥"
                        type="text"
                        autocomplete="off"
                        placeholder="划线价格"
                      />
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="排序" {...formItemLayout}>
                {type === 'view'
                  ? model.sort
                  : getFieldDecorator('sort', {
                      initialValue: model.sort,
                      rules: [
                        {
                          required: true,
                          message: '排序必填',
                        },
                        {
                          max: 9,
                          message: '最长9个字符',
                        },
                        rulesReg('number'),
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        placeholder="排序"
                        maxLength={9}
                        style={{ width: '94%' }}
                      />
                    )}
                &nbsp;&nbsp;
                <Tooltip placement="right" title="排序默认为从大到小(降序)">
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="首页推荐" {...formItemLayout}>
                {type === 'view'
                  ? model.recommended === true
                    ? '是'
                    : '否'
                  : getFieldDecorator('recommended', {
                      initialValue: model.recommended,
                      rules: [],
                    })(
                      <Switch
                        checkedChildren="是"
                        unCheckedChildren="否"
                        checked={model.recommended}
                        onChange={value => {
                          model.recommended = value === true ? 1 : 0;
                        }}
                      />
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="作为商品" {...formItemLayout}>
                {type === 'view'
                  ? model.asProduct === false
                    ? '配件或赠品销售'
                    : '正常商品'
                  : getFieldDecorator('asProduct', {
                      initialValue: model.asProduct === false ? 0 : 1,
                      rules: [],
                    })(
                      <RadioGroup
                        onChange={value => {
                          if (value.target.value === 0) {
                            model.asProduct = false;
                            model.recommended = false;
                          } else {
                            model.asProduct = true;
                            model.recommended = true;
                          }
                        }}
                      >
                        <Radio value={1}>正常商品</Radio>
                        <Radio value={0}>配件或赠品销售</Radio>
                      </RadioGroup>
                    )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="商家在线资源" {...formItemLayout}>
                {type === 'view'
                  ? model.resKindName
                  : getFieldDecorator('resKindId', {
                      initialValue:
                        model.resKindId && model.resKindId !== ''
                          ? this.splitStr(model.resKindId)
                          : [],
                    })(
                      <Select mode="multiple" style={{ width: '100%' }} placeholder="请选择">
                        {uiUtils.getOptionList(this.props.resKindIdList)}
                      </Select>
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="商家备注" {...formItemLayout}>
                {type === 'view'
                  ? model.remark
                  : getFieldDecorator('remark', {
                      initialValue: model.remark,
                      rules: [
                        {
                          max: 128,
                          message: '最长128个字符',
                        },
                      ],
                    })(<TextArea type="text" autocomplete="off" placeholder="商家备注" />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="短名称" {...formItemLayout}>
                {type === 'view'
                  ? model.productNameSub
                  : getFieldDecorator('productNameSub', {
                      initialValue: model.productNameSub,
                      rules: [
                        {
                          max: 1024,
                          message: '最长1024个字符',
                        },
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="短名称" />)}
              </FormItem>
            </Col>
          </Row>
          <Card
            title="图片信息"
            headStyle={{ backgroundColor: '#f8f8f8' }}
            style={{ marginTop: '10px' }}
          >
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...braftEditorLayout}>
                <FormItem
                  label="封面图片"
                  extra="支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：500X500;"
                  {...braftEditorFormItemLayout}
                >
                  {getFieldDecorator('imageCover', {
                    initialValue: model.imageCover,
                    rules: [
                      {
                        required: true,
                        message: '封面图片必上传',
                      },
                    ],
                  })(
                    <div className="clearfix">
                      <Upload
                        {...imageCoverProps}
                        listType="picture-card"
                        onPreview={this.handleUploadImgPreview}
                      >
                        {this.state.imgList && this.state.imgList.length >= 1 ? null : uploadButton}
                      </Upload>
                      <Modal
                        visible={this.state.previewImgVisible}
                        footer={null}
                        onCancel={() => this.setState({ previewImgVisible: false })}
                      >
                        <img
                          alt="imgExample"
                          style={{ width: '100%' }}
                          src={this.state.previewImg}
                        />
                      </Modal>
                    </div>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...braftEditorLayout}>
                <FormItem
                  label="商品相册"
                  extra="支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：750X590;"
                  {...braftEditorFormItemLayout}
                >
                  {getFieldDecorator('images', {
                    initialValue: model.images,
                    rules: [
                      {
                        required: true,
                        message: '商品相册必上传',
                      },
                    ],
                  })(
                    <div className="clearfix">
                      <Upload
                        {...iconProps}
                        listType="picture-card"
                        onPreview={this.handleUploadIconPreview}
                      >
                        {this.state.iconList && this.state.iconList.length >= 6
                          ? null
                          : uploadButton}
                      </Upload>
                      <Modal
                        visible={this.state.previewIconVisible}
                        footer={null}
                        onCancel={() => this.setState({ previewIconVisible: false })}
                      >
                        <img
                          alt="imgExample"
                          style={{ width: '100%' }}
                          src={this.state.previewIcon}
                        />
                      </Modal>
                    </div>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...braftEditorLayout}>
                <FormItem label="微信二维码" {...braftEditorFormItemLayout}>
                  {getFieldDecorator('wxQrCode', {
                    initialValue: model.wxQrCode,
                    rules: [],
                  })(
                    <div className="clearfix">
                      <DefaultImage style={{ width: '50%', height: '50%' }} src={model.wxQrCode} />
                    </div>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <Card
            title="物流信息"
            headStyle={{ backgroundColor: '#f8f8f8' }}
            style={{ marginTop: '10px' }}
          >
            {/*<Row gutter={{...rowGutterPxLayout}}>
              <Col {...colSpanLayout}>
                <FormItem label="是否包邮" {...formItemLayout}>
                  {type === 'view'
                    ? model.asPostage === false
                      ? '不包邮'
                      : '包邮'
                    : getFieldDecorator('asPostage', {
                      initialValue: model.asPostage === false ? 0 : 1,
                      rules: [],
                    })(
                      <RadioGroup onChange={value => {
                        model.asPostage = value.target.value === 0 ? false : true;
                      }}>
                        <Radio value={0}>不包邮</Radio>
                        <Radio value={1}>包邮</Radio>
                      </RadioGroup>
                    )}
                </FormItem>
              </Col>
            </Row>*/}

            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <FormItem label="运费类型" {...formItemLayout}>
                  {type === 'view'
                    ? this.getDeliveryTypeName(model.deliveryType)
                    : getFieldDecorator('deliveryType', {
                        initialValue: model.deliveryType,
                        rules: [],
                      })(
                        <Select
                          style={{ width: '100%' }}
                          onChange={value => {
                            model.deliveryType = value;
                          }}
                        >
                          <option value={1}>统一运费</option>
                          <option value={2}>满x包邮，否则y元</option>
                          <option value={3}>满xx件包邮，否则yy元</option>
                          <option value={4}>运费模板</option>
                        </Select>
                      )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ ...rowGutterPxLayout }}>
              {model.deliveryType === 4 && (
                <Col {...colSpanLayout}>
                  <FormItem label="运费模板id" {...formItemLayout}>
                    {type === 'view'
                      ? model.deliveryTemplateId
                      : getFieldDecorator('deliveryTemplateId', {
                          initialValue: model.deliveryTemplateId,
                          rules: [rulesReg('number')],
                        })(<Input type="text" autocomplete="off" placeholder="运费模板id" />)}
                  </FormItem>
                </Col>
              )}
            </Row>
            <Row gutter={{ ...rowGutterPxLayout }}>
              {(model.deliveryType === 2 || model.deliveryType === 3) && (
                <Col {...colSpanLayout}>
                  <FormItem label="免运费条件x" {...formItemLayout}>
                    {type === 'view'
                      ? `￥${numeral(model.deliveryBase).format('0,0.00')}`
                      : getFieldDecorator('deliveryBase', {
                          initialValue: model.deliveryBase,
                          rules: [rulesReg('money_0_999999')],
                        })(<Input type="text" autocomplete="off" placeholder="免运费起始条件x" />)}
                  </FormItem>
                </Col>
              )}
              {model.deliveryType !== 4 && (
                <Col {...colSpanLayout}>
                  <FormItem label="运费y" {...formItemLayout}>
                    {type === 'view'
                      ? `￥${numeral(model.deliveryFee).format('0,0.00')}`
                      : getFieldDecorator('deliveryFee', {
                          initialValue: model.deliveryFee,
                          rules: [rulesReg('money_0_999999')],
                        })(
                          <Input
                            addonBefore="￥"
                            type="text"
                            autocomplete="off"
                            placeholder="运费y"
                          />
                        )}
                  </FormItem>
                </Col>
              )}
            </Row>
          </Card>
          <Card
            title="其他信息"
            headStyle={{ backgroundColor: '#f8f8f8' }}
            style={{ marginTop: '10px' }}
          >
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <FormItem label="商品状态" {...formItemLayout}>
                  {type === 'view'
                    ? this.getStatusName(model.status)
                    : getFieldDecorator('status', {
                        initialValue: model.status,
                        rules: [],
                      })(
                        <Select
                          style={{ width: '100%' }}
                          onChange={value => {
                            model.status = value;
                          }}
                        >
                          <option value={2}>上架</option>
                          <option value={0}>自定义上架时间</option>
                          <option value={1}>暂不售卖，放入仓库</option>
                        </Select>
                      )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ ...rowGutterPxLayout }}>
              {model.status === 0 && (
                <Col {...colSpanLayout}>
                  <FormItem label="上架时间" {...formItemLayout}>
                    {type === 'view'
                      ? model.shelvesTime
                      : getFieldDecorator('shelvesTime', {
                          initialValue: moment(
                            model.shelvesTime === undefined ? moment() : model.shelvesTime,
                            'YYYY-MM-DD HH:mm:ss'
                          ),
                          rules: [],
                        })(
                          <DatePicker
                            showTime
                            placeholder="请选择上架时间"
                            defaultValue={moment(
                              model.shelvesTime === undefined ? moment() : model.shelvesTime,
                              'YYYY-MM-DD HH:mm:ss'
                            )}
                          />
                        )}
                  </FormItem>
                </Col>
              )}
            </Row>
          </Card>
          <Card
            title="规格参数"
            headStyle={{ backgroundColor: '#f8f8f8' }}
            style={{ marginTop: '10px', marginBottom: '10px' }}
          >
            <Row gutter={{ ...rowGutterPxLayout }}>
              {type !== 'view' && (
                <Button onClick={this.addSkuKey} style={{ marginLeft: '10px' }}>
                  添加规格
                </Button>
              )}

              <form>
                {this.state.skuKeys.map((item, index) => (
                  <Row>
                    {item.status !== 3 && (
                      <Row gutter={{ ...rowGutterPxLayout }}>
                        <Col {...colSpanLayout}>
                          <FormItem label="规格名" {...formItemLayout}>
                            {this.props.form.getFieldDecorator(`guigeming-${index}`, {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入规格名',
                                },
                                {
                                  max: 32,
                                  message: '最长32个字符',
                                },
                              ],
                              initialValue: item.name,
                            })(
                              <Input
                                placeholder="每个规格名必须不一致"
                                disabled={type === 'view'}
                                onChange={e => {
                                  item.name = e.currentTarget.value;
                                  const { skuKeys: newSkukeys } = this.state;
                                  this.setState({
                                    skuKeys: newSkukeys,
                                  });

                                  const key1 = `skuKey${index}`;
                                  const flagState = {
                                    flag: true,
                                  };
                                  for (let i = 0; i < this.state.skuCols.length; i += 1) {
                                    if (this.state.skuCols[i].key === key1) {
                                      flagState.flag = false;
                                      this.state.skuCols[i].title = e.currentTarget.value;
                                    }
                                  }

                                  if (flagState.flag) {
                                    this.state.skuCols.unshift({
                                      title: e.currentTarget.value,
                                      key: key1,
                                      dataIndex: key1,
                                      render: (text, recode, newindex) => (
                                        <FormItem style={{ margin: 0 }}>
                                          {this.props.form.getFieldDecorator(
                                            `${key1}-${newindex}`,
                                            {
                                              rules: [
                                                {
                                                  required: true,
                                                  message: '请输入规格值',
                                                },
                                              ],
                                              initialValue: text,
                                            }
                                          )(
                                            <Input
                                              disabled={type === 'view'}
                                              onChange={event => {
                                                this.state.skuRows[newindex][key1] =
                                                  event.currentTarget.value;
                                                if (item.specValue.length > 0) {
                                                  for (
                                                    let i = 0;
                                                    i < item.specValue.length;
                                                    i += 1
                                                  ) {
                                                    if (item.specValue[i].code === newindex) {
                                                      item.specValue[i].value =
                                                        event.currentTarget.value;
                                                      return;
                                                    }
                                                  }
                                                }
                                                item.specValue.push({
                                                  code: newindex,
                                                  value: event.currentTarget.value,
                                                });
                                              }}
                                            />
                                          )}
                                        </FormItem>
                                      ),
                                    });
                                  }
                                  const { skuCols: newSkuCols } = this.state;
                                  this.setState({
                                    skuCols: newSkuCols,
                                  });
                                }}
                              />
                            )}
                          </FormItem>
                        </Col>
                        <Col>
                          <a
                            hidden={type === 'view'}
                            onClick={() => {
                              this.delSkuKey(item, index);
                            }}
                          >
                            <Tooltip
                              title={
                                <FormattedMessage
                                  id="ours.curd.list.delete"
                                  defaultMessage="删除"
                                />
                              }
                            >
                              <Icon type="delete" />
                            </Tooltip>
                          </a>
                        </Col>
                      </Row>
                    )}
                  </Row>
                ))}
              </form>
            </Row>
            <Table
              dataSource={this.state.skuRows}
              pagination={false}
              bordered
              style={{ marginTop: '20px' }}
              scroll={{ x: 1200 }}
            >
              {this.state.skuCols.map(item => (
                <Column
                  key={item.key}
                  title={item.title}
                  dataIndex={item.dataIndex}
                  render={item.render}
                  width={item.width}
                  fixed={item.fixed}
                />
              ))}
            </Table>

            {type !== 'view' && (
              <Button onClick={this.addRow} style={{ marginTop: '20px' }}>
                添加一行
              </Button>
            )}
          </Card>
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="商品详情"
          >
            <div>
              {getFieldDecorator('description', {
                initialValue: BraftEditor.createEditorState(model.description),
              })(
                <BraftEditor
                  className={styles.my_editor}
                  placeholder="请输入商品详情"
                  onChange={editorState => {
                    // eslint-disable-next-line react/no-unused-state
                    this.setState({ editorState });
                  }}
                  extendControls={extendControls}
                  {...inputCodeDisabledForView}
                  {...editorProps}
                />
              )}
            </div>
          </Card>
        </Form>
      </div>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
